package com.anjie.powerproject.strategy.controller;

import com.anjie.powerproject.entity.GraphInfo;
import com.anjie.powerproject.entity.HistoryData;
import com.anjie.powerproject.entity.StrategyOutput;
import com.anjie.powerproject.service.GraphInfoService;
import com.anjie.powerproject.service.PredictDataService;
import com.anjie.powerproject.strategy.enums.StrategyEnums;
import com.anjie.powerproject.strategy.service.HistoryDataService;
import com.anjie.powerproject.strategy.service.StrategyOutService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import com.anjie.powerproject.util.GenerateDemoData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("strategy")
public class StrategyGenerateController {
    @Autowired
    private StrategyOutService strategyOutService;
    @Autowired
    private HistoryDataService historyDataService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Deprecated
    public int getGraphIdDeprecated() throws ParseException {
        Date date = new Date();
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        int graphId = graphInfoList.get(0).getGraphId();
        for (GraphInfo g:graphInfoList){
            Date startTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + g.getGraphStartTime());
            Date endTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + g.getGraphEndTime());
            // 如果终止时间小于起始时间，说明属于跨年的情况
            if (endTime.before(startTime)) {
                Date middleTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "12-31");
                endTime.setYear(endTime.getYear() + 1);
                if (date.after(startTime) && date.before(middleTime) || date.before(endTime) && date.after(middleTime) || date.equals(middleTime)) {
                    graphId = g.getGraphId();
                }
            } else {
                if (date.after(startTime)&&date.before(endTime)){
                    graphId = g.getGraphId();
                    //break;
                }
            }
        }
        return graphId;
    }

//    public Integer getGraphId(Date date) throws ParseException {
//        // 目前的图谱不会出现时间重合的现象了，但是可能出现时间空缺的时候，这个时候默认获取上一张图谱
//        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
//        for (GraphInfo graphInfo : graphInfoList) {
//            Date startTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphStartTime());
//            startTime = DateUtils.plusOrMinusDay(startTime, -1).getTime();
//            Date endTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphEndTime());
//            endTime = DateUtils.plusOrMinusDay(endTime, 1).getTime();
//            // 如果终止时间小于起始时间，说明属于跨年的情况
//            if (endTime.before(startTime)) {
////                Date middleL = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "12-31");
////                Date middleR = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "01-01");
////                if (date.after(startTime) && date.before(middleL) || date.before(endTime) && date.after(middleR) || date.equals(middleR) || date.equals(middleL)) {
////                    return graphInfo.getGraphId();
////                }
////            	Date middleL = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "12-31");
////                Date middleR = DateUtils.ymdFormat.parse(1900 + date.getYear() + 1 + "-" + "01-01");
//                endTime.setYear(endTime.getYear() + 1);
//                if (date.after(startTime) && date.before(endTime)) {
//                    return graphInfo.getGraphId();
//                }
//            } else {
//                if (date.after(startTime)&&date.before(endTime)){
//                    return graphInfo.getGraphId();
//                }
//            }
//        }
//        // 如果执行到这里，只能说明出现了空缺，找寻前一张图谱
//        GraphInfo beforeGraphInfo = graphInfoService.findBeforeGraphInfo(date);
//        // 原则上这里一定不为空
//        assert beforeGraphInfo != null;
//
//        return beforeGraphInfo.getGraphId();
//    }
    public Integer getGraphId(Date date) throws ParseException {
        // 目前的图谱不会出现时间重合的现象了，但是可能出现时间空缺的时候，这个时候默认获取上一张图谱
//        Date date = new Date();
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        for (GraphInfo graphInfo : graphInfoList) {
            Date startTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphStartTime());
            startTime = DateUtils.plusOrMinusDay(startTime, -1).getTime();
            Date endTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphEndTime());
            endTime = DateUtils.plusOrMinusDay(endTime, 1).getTime();
            // 如果终止时间小于起始时间，说明属于跨年的情况
            if (endTime.before(startTime)) {
//                Date middleL = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "12-31");
//                Date middleR = DateUtils.ymdFormat.parse(1900 + date.getYear() + 1 + "-" + "01-01");
                
//                endTime.setYear(endTime.getYear() + 1);
//            	startTime.setYear(startTime.getYear() - 1);
//                if (date.after(startTime) && date.before(middleL) || date.before(endTime) && date.after(middleR) || date.equals(middleR) || date.equals(middleL)) {
//                    return graphInfo.getGraphId();
//                }
//                if (date.after(startTime) && date.before(endTime)) {
//                    return graphInfo.getGraphId();
//                }
            	if (date.after(startTime)) {
            		endTime.setYear(endTime.getYear() + 1);
            	}
            	else if(date.before(endTime)) {
            		startTime.setYear(startTime.getYear() - 1);
            	}
            	
            	if (date.after(startTime) && date.before(endTime)) {
                  return graphInfo.getGraphId();
                }
            	
            } else {
                if (date.after(startTime)&&date.before(endTime)){
                    return graphInfo.getGraphId();
                }
            }
        }
        // 如果执行到这里，只能说明出现了空缺，找寻前一张图谱
        GraphInfo beforeGraphInfo = graphInfoService.findBeforeGraphInfo(date);
        // 原则上这里一定不为空
        assert beforeGraphInfo != null;
        return beforeGraphInfo.getGraphId();
    }
    
    
    @GetMapping("gen/{type}")
    public Map<String, Object> getStrategyWithType(@PathVariable("type") Integer type, @RequestParam(value = "date", defaultValue = "none") String date) throws IOException, ParseException {
        System.out.println("type: "+type+"    date: "+date);
        int graphId = 0;
        if (date.equals("none")) {
            graphId = getGraphId(new Date());
        } else {
            graphId = getGraphId(DateUtils.ymdFormat2.parse(date));
        }

        StrategyEnums strategyEnums = StrategyEnums.getStrategyEnumsByType(type);
        if (strategyEnums != null) {
            List<StrategyOutput> strategyOutputs = null;
            List<HistoryData> historyDataList = null;
            if (date.equals("none")) {
                // 默认访问今日的策略信息
                strategyOutputs = strategyOutService.getStrategyOutputsByDateAndType(new Date(), type, graphId);
                historyDataList = historyDataService.getHistoryDataListByDateAndType(new Date(), type, graphId);
            } else {
                //访问指定日期的策略信息
                try {
                    strategyOutputs = strategyOutService.getStrategyOutputsByDateAndType(DateUtils.ymdFormat2.parse(date), type, graphId);
                    historyDataList = historyDataService.getHistoryDataListByDateAndType(DateUtils.ymdFormat2.parse(date), type, graphId);
                } catch (ParseException e) {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("error", "日期格式错误");
                    return resultMap;
                }
            }

            // 若获取到数据
            if (strategyOutputs != null && strategyOutputs.size() != 0 && historyDataList != null && historyDataList.size() != 0) {
                strategyOutputs.stream().forEach(item->item.setInfoTime(item.getInfo().split(" ")[0]));
                strategyOutputs.stream().forEach(item->item.setInfoContent(StringUtils.join(item.getInfo().split(" "), " ", 1, item.getInfo().split(" ").length)));

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("strategyOutput", strategyOutputs);

                for (HistoryData historyData : historyDataList) {
                    // bug: 当history_data中包含的数据不是list时要另外考虑
                    if (historyData.getAlias().equals("path") || historyData.getAlias().equals("node")) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(","));
                    } else if (historyData.getData().indexOf(",") != -1) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(","));
                    } else if (historyData.getData().indexOf(" ") != -1) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(" "));
                    } else {
                        resultMap.put(historyData.getAlias(), historyData.getData());
                    }
                }
                return resultMap;
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("error", "没有策略");
                return resultMap;
            }
        } else {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("error", "没有这样的策略");
            return resultMap;
        }
    }

    @GetMapping("gen")
    public Map<String, Object> getStrategy(@RequestParam(value = "date", defaultValue = "none") String date) throws IOException, ParseException {
        int graphId = 0;
        System.out.println("gen202");
//        date="2022-02-22 00:00:00";
        System.out.println("测试日期:" + date);
        if (date.equals("none")) {
            graphId = getGraphId(new Date());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String s = simpleDateFormat.format(new Date());
            date=s;
        } else {
            graphId = getGraphId(DateUtils.ymdFormat2.parse(date));
        }
        System.out.println("图谱id:" + graphId);
        // 获取图谱绑定的策略
        int type = 1001;
        String start_work_time="";
        Integer start_work_time_hour=0;
        Integer start_work_time_minute=0;
        String end_work_time="";
        Integer end_work_time_hour=0;
        Integer end_work_time_minute=0;
        GraphInfo graphInfo = graphInfoService.findGraphInfoById(graphId);
        if (graphInfo != null) {
            if(graphInfo.getStrategyType() != null){
                type = graphInfo.getStrategyType();
            }
            //获取当前作息的工作时间
            start_work_time=graphInfo.getStartWorkTime();//08:30
            end_work_time =graphInfo.getEndWorkTime();//17:30
        }
        start_work_time_hour=Integer.parseInt(start_work_time.split(":")[0]);
        start_work_time_minute=Integer.parseInt(start_work_time.split(":")[1]);
        end_work_time_hour=Integer.parseInt(end_work_time.split(":")[0]);
        end_work_time_minute=Integer.parseInt(end_work_time.split(":")[1]);
        String startWorkTime="";
        String endWorkTime="";

        startWorkTime=DateUtils.getLocalDateString(DateUtils.ymdhmFormat,DateUtils.getDateWithHourAndMinute(DateUtils.ymdFormat2.parse(date),start_work_time_hour,start_work_time_minute).getTime());
        Calendar calendar = new GregorianCalendar();
        calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0,4)));
        calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(4,6))-1); // 11 = 十二月
        calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(6))); // 表示09年最后一天
        calendar.add(Calendar.DATE, -1);
        String yesterday=DateUtils.ymdFormat2.format(calendar.getTime());
        String yesterdayEndWorkTime=DateUtils.getLocalDateString(DateUtils.ymdhmFormat,DateUtils.getDateWithHourAndMinute(DateUtils.ymdFormat2.parse(yesterday),end_work_time_hour,end_work_time_minute).getTime());
//        System.out.println("yesterdayEndWorkTime："+yesterdayEndWorkTime);

        endWorkTime=DateUtils.getLocalDateString(DateUtils.ymdhmFormat,DateUtils.getDateWithHourAndMinute(DateUtils.ymdFormat2.parse(date),end_work_time_hour,end_work_time_minute).getTime());
        System.out.println("startWorkTime:" + startWorkTime);//2020-08-21 08:30
        System.out.println("endWorkTime:" + endWorkTime);//2020-08-21 17:30

        StrategyEnums strategyEnums = StrategyEnums.getStrategyEnumsByType(type);
        if (strategyEnums != null) {
            List<StrategyOutput> strategyOutputs = null;
            List<HistoryData> historyDataList = null;
            //访问指定日期的策略信息
            try {
                System.out.println(date);
                System.out.println(type);
                System.out.println(graphId);
                System.out.println("date:"+DateUtils.ymdFormat2.parse(date)+"----"+"startWorkTime:"+startWorkTime);

                //筛选出策略 结束日期在 昨天17.30-今天17.30的策略
//                strategyOutputs = strategyOutService.getStrategyOutputsByDateAndTypeAndEndTime(DateUtils.ymdFormat2.parse(date), type, graphId,startWorkTime);
                strategyOutputs = strategyOutService.getStrategyOutputsByDateAndTypeAndEndTime(type, graphId,yesterdayEndWorkTime,endWorkTime);
                historyDataList = historyDataService.getHistoryDataListByDateAndType(DateUtils.ymdFormat2.parse(date), type, graphId);
                System.out.println("测试日期:" + date);
//                for(StrategyOutput s:strategyOutputs){
//                    System.out.println(s.getStartTime()+"    "+s.getEndTime()+"     "+s.getInfo());
//                }
                System.out.println("测试strategyOutputs: " + strategyOutputs);
                System.out.println("测试:" + historyDataList);
            } catch (ParseException e) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("error", "日期格式错误");
                return resultMap;
            }

            // 若获取到数据
            if (strategyOutputs != null && strategyOutputs.size() != 0 && historyDataList != null && historyDataList.size() != 0) {
                strategyOutputs.stream().forEach(item->item.setInfoTime(item.getInfo().split(" ")[0]));
                strategyOutputs.stream().forEach(item->item.setInfoContent(StringUtils.join(item.getInfo().split(" "), " ", 1, item.getInfo().split(" ").length)));

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("strategyOutput", strategyOutputs);

                for (HistoryData historyData : historyDataList) {
                    // bug: 当history_data中包含的数据不是list时要另外考虑
                    if (historyData.getAlias().equals("path") || historyData.getAlias().equals("node")) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(","));
                    } else if (historyData.getData().indexOf(",") != -1) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(","));
                    } else if (historyData.getData().indexOf(" ") != -1) {
                        resultMap.put(historyData.getAlias(), historyData.getData().split(" "));
                    } else {
                        resultMap.put(historyData.getAlias(), historyData.getData());
                    }
                }

                resultMap.put("strategyType", strategyEnums.getName());
                return resultMap;
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("error", "没有策略");
                return resultMap;
            }
        } else {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("error", "没有这样的策略");
            return resultMap;
        }
    }


    @Autowired
    private PredictDataService predictDataService;

//    @Autowired
//    private ColdStrategy coldStrategy;
    private HashMap<String, String> eng2Chs = new HashMap<String, String>();
    private HashMap<String, String> testChs = new HashMap<String, String>();
    private HashMap<String, String> winGraph = new HashMap<String, String>();
    private HashMap<String, String> sumGraph = new HashMap<String, String>();

    void init() {
        testChs.put("dianliang", "电量");
        testChs.put("xuqiu", "需求计算");
        testChs.put("xinfeng", "新风");
        testChs.put("xuneng", "水蓄能");
        testChs.put("dimaiguan", "地埋管");
        testChs.put("zhujizhigong", "主机直供");
        testChs.put("zhujixuleng", "主机蓄冷");
        testChs.put("nuandian", "暖电");
        testChs.put("guangre", "光热");
    }

    void init1() { //夏季
        eng2Chs.clear();
        eng2Chs.put("dimaiguan", "免费冷直供地板");//免费冷供冷量
        eng2Chs.put("xinfeng", "免费冷直供新风");//新风机组直膨冷量
        eng2Chs.put("xuneng", "水蓄能罐放冷至地板");//水蓄能放冷量,
        eng2Chs.put("w2xinfeng", "水蓄能罐放冷至新风");
        eng2Chs.put("zhujizhigong", "主机直供地板");//主机直供地板
        eng2Chs.put("zhujixuleng", "主机蓄冷至水蓄能罐");//主机蓄冷量
        eng2Chs.put("guangre", "太阳能蓄热到暖电");
        eng2Chs.put("addix", "暖电放热至生活热水换热器");
    }

    void init2() {//冬季
        eng2Chs.clear();
        eng2Chs.put("xuneng", "水蓄能罐放热至地板");//水蓄能放冷量,
        eng2Chs.put("zhujizhigong", "主机直供地板");//主机直供地板
        eng2Chs.put("zhujixuleng", "主机蓄热至水蓄能罐");//主机蓄冷量
        eng2Chs.put("guangre", "太阳能直供地板");
        eng2Chs.put("addix", "主机蓄热至生活热水换热器");
    }

    void getSumGraphPath(){
        sumGraph.put("guangre","3#7,7#8");
        sumGraph.put("xuneng","1#6");
        sumGraph.put("dimaiguan","9#6");
        sumGraph.put("xinfeng","0#2,9#2");
        sumGraph.put("addix","3#7,7#8");
        sumGraph.put("zhujixuleng","4#5,5#1");
        sumGraph.put("w2xinfeng","1#2,0#2");
        sumGraph.put("zhujizhigong","4#5,5#2,5#6");
        sumGraph.put("addix","3#7,7#8");
    }

    void getWinGraphPath(){
        winGraph.put("xuneng","2#7");
        winGraph.put("guangre","1#7");
        winGraph.put("addix","3#9");
        winGraph.put("zhujizhigong","3#7");
        winGraph.put("zhujixuleng","4#3,3#2");
    }

    float convert(float num){
        return (float)(Math.round(num*10))/10;
    }

    //用于处理过渡季节
    Map<String, Object>  getCross(float tem1, float tem2, float hum1, float hum2, int flag, int person){

        Map<String, float[]> speData = getSpecificData(Float.valueOf(tem1), Float.valueOf(tem2), Float.valueOf(hum1), Float.valueOf(hum2), flag, person);
        String appendDLPoint[]  = {"bangong","zhaoming","xiaofang","other"};

        float dls[] = speData.get("dianliang");
        for(int i = 0;i<4;++i){
            float single[] = speData.get(appendDLPoint[i]);
            for(int j = 0;j<24;++j){
                dls[j] += single[j];
                dls[j] = convert(dls[j]);
            }
        }

        String crossAns = "3#7,7#8";//表示返回的图谱路径
        String NodeAns = "3,7,8";//
        String retPath = "(23:00~6:00)        暖电放热至生活热水换热器,(7:00~17:00)        太阳能蓄热到暖电";
        Map res = new HashMap<String, Object>();
        float nls[] = new float[24];//为每个小时预测的能量值

        res.put("nls", nls);
        res.put("dls", speData.get("dianliang"));
        res.put("path", crossAns.split(","));
        res.put("node", NodeAns.split(","));
        res.put("gongkuang", retPath.toString().split(","));
        return res;
    }

    Map<String, float[]> getSpecificData(float tem1, float tem2, float hum1, float hum2, int flag, int person) {
        return GenerateDemoData.doGenerate(tem1, tem2, hum1, hum2, flag, person); //flag 1_夏季 2_冬季
    }

    public Map<String, Object> getWinter(String tem1, String tem2, int flag, int person) {
        init2();
        getWinGraphPath();
        Map<String, float[]> speData = getSpecificData(Float.valueOf(tem1), Float.valueOf(tem2), 10, 30, flag, person);

        String appendDLPoint[]  = {"bangong","zhaoming","xiaofang","other"};
        String appendNLPoint[]  = {"meetingData","restaurantData"};

        float dls[] = speData.get("dianliang");
        for(int i = 0;i<4;++i){
            float single[] = speData.get(appendDLPoint[i]);
            for(int j = 0;j<24;++j){
                dls[j] += single[j];
                dls[j] = convert(dls[j]);
            }
        }

        float nls[] = speData.get("xuqiu");
        for(int i = 0;i<2;++i){
            float single[] = speData.get(appendNLPoint[i]);
            for(int j = 0;j<24;++j){
                nls[j] += single[j];
                nls[j] = convert(nls[j]);
            }
        }


        Iterator<String> iter = speData.keySet().iterator();
        while (iter.hasNext()) {
            String str = iter.next();
            if (str.equals("temperature") || str.equals("humidity")||str.equals("bangong") || str.equals("zhaoming")||str.equals("xiaofang") || str.equals("other")||str.equals("meetingData") || str.equals("restaurantData")) {
                iter.remove();
            }
        }
        for (Map.Entry<String, float[]> i : speData.entrySet()) {

            System.out.print("Key:" + testChs.get(i.getKey()) + "    ");
            for (int j = 0; j < i.getValue().length; ++j) {
                System.out.print(" " + i.getValue()[j]);
            }
            System.out.println();
        }
        Map<String, ArrayList<Integer>> condition = new HashMap<String, ArrayList<Integer>>();
        HashMap<String, String> str2Hour = new HashMap<String, String>();

        Map res = new HashMap<String, Object>();

        Object[] keys = speData.keySet().toArray();
        for (int i = 0; i < 24; ++i) {
            float xuneng = 0, zhujizhigong = 0, zhujixuleng = 0, guangre = 0;//为与夏天保持一致，这里叫主机蓄冷
            //xuneng 水蓄能放热量,  主机直供热量 diyuanrebeng ,guangre 太阳能直供热量;
            for (int j = 0; j < keys.length; ++j) {
                String name = keys[j].toString();
                float nl = speData.get(name)[i];
                if (nl != 0) {
                    if (condition.get(name) == null) {
                        condition.put(name, new ArrayList<Integer>());
                    }
                    if (name == "zhujizhigong") {
                        if (i >= 11 && i <= 18) condition.get(name).add(i);//11:00~18:00如果供能不为0，说明开启了主机功能策略;
                    } else {
                        condition.get(name).add(i);
                    }
                }
            }
        }

        Object[] ckeys = condition.keySet().toArray();
        for (int i = 0; i < ckeys.length; ++i) {
            String conName = ckeys[i].toString();
            if (conName == "dianliang" || conName == "xuqiu" || conName == "xinfeng" || conName == "nuandian") continue;
            ArrayList<Integer> conHour = condition.get(conName);
            if (conHour.size() == 0) continue;
            ArrayList<Integer> tmp = new ArrayList<>();
            for (int k = 0; k < conHour.size(); ++k) tmp.add(conHour.get(k));
            for (int j = 1; j < tmp.size() - 1; ++j) {
                if (tmp.get(j) == tmp.get(j - 1) + 1 && tmp.get(j) + 1 == tmp.get(j + 1)) {
                    conHour.set(j, -1);
                }
            }
        }

        for (int i = 0; i < ckeys.length; ++i) {
            StringBuilder temp = new StringBuilder();
            String cname = ckeys[i].toString();
            if (cname == "dianliang" || cname == "xuqiu"||cname == "zhujixuleng") continue;
            ArrayList<Integer> Hour = condition.get(cname);
            ArrayList<String> conHour = new ArrayList<>();
            for (int j = 0; j < Hour.size(); ++j) {
                if (Hour.get(j) != -1) {
                    conHour.add(Hour.get(j) + ":00");
                }
            }
            if (conHour.size() == 0){
                continue;
            }else{
                if(conHour.size() == 1){
                    conHour.add( String.valueOf((Integer.valueOf(conHour.get(0).split(":")[0]) + 1)%24) + ":00");
                }
            }
            int x = 0;
            while (x + 2 <= conHour.size()) {
                if (x != 0) temp.append("、");
                temp.append(conHour.get(x) + "~" + conHour.get(x + 1));
                x += 2;
            }
            if (x != conHour.size()) {
                if (conHour.size() > 2) {
                    temp.append("、" + conHour.get(x) + "~" + String.valueOf((Integer.valueOf(conHour.get(x).split(":")[0]) + 1)%24) + ":00");
                } else {
                    temp.append(conHour.get(x) + "~" + String.valueOf((Integer.valueOf(conHour.get(x).split(":")[0]) + 1)%24) + ":00");
                }
            }
            str2Hour.put(cname, temp.toString());
        }

        StringBuilder retPath = new StringBuilder();
        StringBuilder engPath = new StringBuilder();
        int f = 0;
        for (int j = 0; j < keys.length; ++j) {
            String name = keys[j].toString();
            if (name == "dianliang" || name == "xuqiu" || name == "xinfeng" || name == "dimaiguan"||name == "nuandian") continue;
            if (str2Hour.get(name) != null) {
                if (f != 0){
                    retPath.append(",");
                    engPath.append(",");
                }
                retPath.append("(" + str2Hour.get(name) + ")" + "        " + eng2Chs.get(name));
                engPath.append(name);
                f++;
            }
        }
        if(str2Hour.get("zhujizhigong") == null&&(Float.valueOf(tem1) +  Float.valueOf(tem2)<0||Float.valueOf(tem1)<-5)){
            retPath.append(",(17:00~18:00)" + "        " + eng2Chs.get("zhujizhigong"));
            engPath.append(",zhujizhigong");
        }// 自定义的补充

        retPath.append(",(23:00~6:00)" + "        " + eng2Chs.get("addix"));
        engPath.append(",addix");
        retPath.append(",(23:00~6:00)" + "        " + eng2Chs.get("zhujixuleng"));
        engPath.append(",zhujixuleng");

        StringBuilder  graphStr =  new StringBuilder();
        String []winGraphArr = engPath.toString().split(",");
        for(int i = 0;i<winGraphArr.length;++i){
            if(i != 0)graphStr.append(",");
            graphStr.append(winGraph.get(winGraphArr[i]));
        }
        Set<String> winPath = new HashSet<>();
        Set<String> winNode = new HashSet<>();
        String [] arr = graphStr.toString().split(",");
        for(int i =0;i<arr.length;++i)winPath.add(arr[i]);
        winPath.add("5#7");
        String winAns = "",NodeAns = "";

        for(int i = 0;i<winPath.toArray().length;++i){
            if(i !=0)winAns += ",";
            winAns += winPath.toArray()[i];
        }

        for(int i = 0;i<winAns.split(",|#").length;++i){
            winNode.add(winAns.split(",|#")[i]);
        }
        for(int i = 0;i<winNode.toArray().length;++i){
            if(i !=0)NodeAns += ",";
            NodeAns += winNode.toArray()[i];
        }

        System.out.println(winAns);
        System.out.println(NodeAns);

        System.out.println("图谱");
        System.out.println(engPath.toString());
        System.out.println();
        System.out.println("最终策略");
        System.out.println(retPath);
        System.out.println();
        res.put("nls", speData.get("xuqiu"));
        res.put("dls", speData.get("dianliang"));
        res.put("path", winAns.split(","));
        res.put("node", NodeAns.split(","));
        res.put("gongkuang", retPath.toString().split(","));
        return res;
    }


    @PostMapping("/getHourData")
    @ResponseBody
    public Map<String, Object> getHourData(String tem1, String tem2, String hum1, String hum2, int flag, int person) {
        init();
        getSumGraphPath();
        if (flag == 0) {
            return getWinter(tem1, tem2, flag, person);
        }else if(Float.valueOf(tem1) >=16&&Float.valueOf(tem2) <26){
            return getCross(Float.valueOf(tem1), Float.valueOf(tem2), Float.valueOf(hum1), Float.valueOf(hum2), flag, person);
        }
        init1();
        Map<String, float[]> speData = getSpecificData(Float.valueOf(tem1), Float.valueOf(tem2), Float.valueOf(hum1), Float.valueOf(hum2), flag, person);


        String appendDLPoint[]  = {"bangong","zhaoming","xiaofang","other"};
        String appendNLPoint[]  = {"meetingData","restaurantData"};

        float dls[] = speData.get("dianliang");
        for(int i = 0;i<4;++i){
            float single[] = speData.get(appendDLPoint[i]);
            for(int j = 0;j<24;++j){
                dls[j] += single[j];
                dls[j] = convert(dls[j]);
            }
        }

        float nls[] = speData.get("xuqiu");
        for(int i = 0;i<2;++i){
            float single[] = speData.get(appendNLPoint[i]);
            for(int j = 0;j<24;++j){
                nls[j] += single[j];
                nls[j] = convert(nls[j]);
            }
        }

        Iterator<String> iter = speData.keySet().iterator();
        while (iter.hasNext()) {
            String str = iter.next();
            if (str.equals("temperature") || str.equals("humidity")||str.equals("bangong") || str.equals("zhaoming")||str.equals("xiaofang") || str.equals("other")||str.equals("meetingData") || str.equals("restaurantData")) {
                iter.remove();
            }
        }
        for (Map.Entry<String, float[]> i : speData.entrySet()) {
            System.out.print("Key:" + testChs.get(i.getKey()) + " " + i.getKey() +  "    ");
            for (int j = 0; j < i.getValue().length; ++j) {
                System.out.print(" " + i.getValue()[j]);
            }
            System.out.println();
        }
        Map<String, ArrayList<Integer>> condition = new HashMap<String, ArrayList<Integer>>();
        HashMap<String, String> str2Hour = new HashMap<String, String>();

        Map res = new HashMap<String, Object>();

        Object[] keys = speData.keySet().toArray();
        for (int i = 0; i < 24; ++i) {
            float dimaiguan = 0, zhujizhigong = 0, zhujixuleng = 0, xuneng = 0, xinfeng = 0;
            //dimaiguan 免费冷供冷量,  主机蓄冷量 diyuanrebeng 主机直供冷量,xuneng 水蓄能放冷量,新风机组直膨冷量 xinfeng;
            for (int j = 0; j < keys.length; ++j) {
                String name = keys[j].toString();
                float nl = speData.get(name)[i];
                if (name == "dimaiguan") {
                    if (condition.get(name) == null) {
                        condition.put(name, new ArrayList<Integer>());
                    }
                    condition.get(name).add(i);
                } else if (name == "addix" && (i <= 6 || i == 23)) {
                    if (condition.get(name) == null) {
                        condition.put(name, new ArrayList<Integer>());
                    }
                    condition.get(name).add(i);
                } else {
                    if (nl != 0) {
                        if (condition.get(name) == null) {
                            condition.put(name, new ArrayList<Integer>());
                        }
                        if (name == "zhujizhigong") {
                            if (i >= 11 && i <= 18) condition.get(name).add(i);//11:00~18:00如果供能量不为0，说明开启了主机供能策略;
                        } else {
                            condition.get(name).add(i);
                        }
                    }
                }
            }
        }

        Object[] ckeys = condition.keySet().toArray();
        for (int i = 0; i < ckeys.length; ++i) {
            String conName = ckeys[i].toString();
            if (conName == "dianliang" || conName == "xuqiu") continue;
            ArrayList<Integer> conHour = condition.get(conName);
            if (conHour.size() == 0) continue;
            ArrayList<Integer> tmp = new ArrayList<>();
            for (int k = 0; k < conHour.size(); ++k) tmp.add(conHour.get(k));
            for (int j = 1; j < tmp.size() - 1; ++j) {
                if (tmp.get(j) == tmp.get(j - 1) + 1 && tmp.get(j) + 1 == tmp.get(j + 1)) {
                    conHour.set(j, -1);
                }
            }
        }

        for (int i = 0; i < ckeys.length; ++i) {
            StringBuilder temp = new StringBuilder();
            String cname = ckeys[i].toString();
            if (cname == "dianliang" || cname == "xuqiu"||cname == "zhujixuleng") continue;
            ArrayList<Integer> Hour = condition.get(cname);
            ArrayList<String> conHour = new ArrayList<>();
            for (int j = 0; j < Hour.size(); ++j) {
                if (Hour.get(j) != -1) {
                    conHour.add(Hour.get(j) + ":00");
                }
            }
            if (conHour.size() == 0){
                continue;
            }else{
                if(conHour.size() == 1){
                    conHour.add( String.valueOf((Integer.valueOf(conHour.get(0).split(":")[0]) + 1)%24) + ":00");
                }
            }
            int x = 0;
            while (x + 2 <= conHour.size()) {
                if (x != 0) temp.append("、");
                temp.append(conHour.get(x) + "~" + conHour.get(x + 1));
                x += 2;
            }
            if (x != conHour.size()) {
                if (conHour.size() > 2) {
                    temp.append("、" + conHour.get(x) + "~" + String.valueOf((Integer.valueOf(conHour.get(x).split(":")[0]) + 1)%24) + ":00");
                } else {
                    temp.append(conHour.get(x) + "~" + String.valueOf((Integer.valueOf(conHour.get(x).split(":")[0]) + 1)%24) + ":00");
                }
            }
            str2Hour.put(cname, temp.toString());
        }

        StringBuilder retPath = new StringBuilder();
        StringBuilder retEngPath = new StringBuilder();
        int f = 0;
        for (int j = 0; j < keys.length; ++j) {
            String name = keys[j].toString();
            if (name == "dianliang" || name == "xuqiu"||name == "nuandian") continue;
            if (str2Hour.get(name) != null) {
                if (f != 0) {
                    retPath.append(",");
                    retEngPath.append(",");
                }
                retPath.append("(" + str2Hour.get(name) + ")" + "        " + eng2Chs.get(name));
                retEngPath.append(name);
                f++;
            }
        }
        if ((Float.valueOf(tem1) + Float.valueOf(tem2)) / 2 > 26 && (Float.valueOf(hum1) + Float.valueOf(hum2)) / 2 > 40) {
            retPath.append(",(" + str2Hour.get("xinfeng") + ")" + "        " + eng2Chs.get("w2xinfeng"));
            retEngPath.append(",w2xinfeng");
        }
        retPath.append(",(23:00~6:00)" + "        " + eng2Chs.get("addix"));
        retEngPath.append(",addix");
        retPath.append(",(23:00~6:00)" + "        " + eng2Chs.get("zhujixuleng"));
        retEngPath.append(",zhujixuleng");
        System.out.println("图谱");
        StringBuilder  graphStr =  new StringBuilder();
        String []sumGraphArr = retEngPath.toString().split(",");
        for(int i = 0;i<sumGraphArr.length;++i){
            if(i != 0)graphStr.append(",");
            graphStr.append(sumGraph.get(sumGraphArr[i]));
        }

        Set<String> sumPath = new HashSet<>();
        Set<String> sumNode = new HashSet<>();
        String [] arr = graphStr.toString().split(",");
        for(int i =0;i<arr.length;++i)sumPath.add(arr[i]);
        sumPath.add("0#4");
        sumPath.add("10#4");
        sumPath.add("10#6");
        String sumAns = "",NodeAns = "";
        for(int i = 0;i<sumPath.toArray().length;++i){
            if(i !=0)sumAns += ",";
            sumAns += sumPath.toArray()[i];
        }
        for(int i = 0;i<sumAns.split(",|#").length;++i){
            sumNode.add(sumAns.split(",|#")[i]);
        }
        for(int i = 0;i<sumNode.toArray().length;++i){
            if(i !=0)NodeAns += ",";
            NodeAns += sumNode.toArray()[i];
        }


        System.out.println(sumAns);
        System.out.println(NodeAns);
        System.out.println("最终策略");
        System.out.println(retPath);
        System.out.println(retEngPath);
        System.out.println();

        res.put("nls", speData.get("xuqiu"));
        res.put("dls", speData.get("dianliang"));
        res.put("path", sumAns.split(","));
        res.put("node", NodeAns.split(","));
        res.put("gongkuang", retPath.toString().split(","));
        return res;
    }

}